package com.yulp.springboot2task.config;

import com.yulp.springboot2task.utils.SpringContext;
import org.quartz.*;

import java.util.Date;
import java.util.Map;

/**
 * @description:
 * @date: 2019/11/4 19:19.
 * @author: yulipeng.
 *
 *
 */
public class SimpleQuartzManager2 {

    private static Scheduler sched = getScheduler();

    private static Scheduler getScheduler() {
        if (sched == null) {
            sched = (Scheduler) SpringContext.getBean("schedulerFactoryBean");
        }
        return sched;
    }

    /**
     * @param jobName          任务名（保持唯一）
     * @param jobGroupName     任务组名
     * @param triggerName      触发器名（保持唯一）
     * @param triggerGroupName 触发器组名
     * @param jobClass         任务
     * @param cron             Cron方式参数：cron表达式；（必填）
     * @param data             传参（无参可传空）
     * @Description: 添加一个定时任务（Cron方式）
     */
    public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName,
                              Class jobClass, Long afterSeconds, String cron, Map<String, String> data) {
        addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, afterSeconds,
                cron, null, null, data);
    }

    /**
     * @param jobName          任务名（保持唯一）
     * @param jobGroupName     任务组名
     * @param triggerName      触发器名（保持唯一）
     * @param triggerGroupName 触发器组名
     * @param jobClass         任务
     * @param intervalInSeconds Simple方式参数1：每间隔多少秒执行一次；（必填）
     * @param repeatCount      Simple方式参数2：共执行n+1次；（必填）
     * @param data             传参（无参可传空）
     * @Description: 添加一个定时任务（Simple方式）
     */
    public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName,
                              Class jobClass, Long afterSeconds,
                              Integer intervalInSeconds, Integer repeatCount, Map<String, String> data) {
        addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, afterSeconds,
                null, intervalInSeconds, repeatCount, data);
    }

    /**
     * @param jobName          任务名
     * @param jobGroupName     任务组名
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClass         任务
     * @param afterSeconds     多少秒后开始执行（立即执行可传0）
     * @param cron             Cron方式参数：cron表达式；（cron或Simple二选一）
     * @param intervalInSeconds Simple方式参数1：每间隔多少秒执行一次；（cron或Simple二选一）
     * @param repeatCount      Simple方式参数2：执行n+1次
     * @param data             传参
     * @Description: 添加一个定时任务
     */
    private static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName,
                              Class jobClass, long afterSeconds, String cron,
                               Integer intervalInSeconds, Integer repeatCount, Map<String, String> data) {

        try {
            // 任务名，任务组，任务执行类
            JobBuilder jobBuilder = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName);
            // 添加传参数据
            if (data != null && !data.isEmpty()) {
                jobBuilder.usingJobData(new JobDataMap(data));
            }

            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            //triggerBuilder.startNow();
            Date date = new Date();
            date.setTime(System.currentTimeMillis() + afterSeconds * 1000);
            triggerBuilder.startAt(date);
            if (cron != null && !"".equals(cron)) {
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            } else {
                triggerBuilder.withSchedule(SimpleScheduleBuilder
                    .simpleSchedule()
                    // 每n秒执行一次
                    .withIntervalInSeconds(intervalInSeconds)
                    // 共执行n+1次
                    .withRepeatCount(repeatCount));
            }

            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobBuilder.build(), triggerBuilder.build());
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @param cron             时间设置，参考quartz说明文档
     * @Description: 修改一个任务的触发时间cron（方式一： 调用 rescheduleJob）
     */
    public static void modifyJobTime(String triggerName, String triggerGroupName, String cron) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }

            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                /** 方式一 ：调用 rescheduleJob */
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                sched.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param jobName
     * @param jobGroupName
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @param cron             时间设置，参考quartz说明文档
     * @Description: 修改一个任务的触发时间cron（方式二： 先删除，然后在创建一个新的Job）
     */
    public static void modifyJobTime(String jobName, String jobGroupName,
                                     String triggerName, String triggerGroupName, String cron) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }

            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                /** 方式二：先删除，然后在创建一个新的Job  */
                JobDetail jobDetail = sched.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                Class<? extends Job> jobClass = jobDetail.getJobClass();
                removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
                addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClass, 0L, cron, null);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @Description: 移除一个任务
     */
    public static void removeJob(String jobName, String jobGroupName,
                                 String triggerName, String triggerGroupName) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            // 停止触发器
            sched.pauseTrigger(triggerKey);
            // 移除触发器
            sched.unscheduleJob(triggerKey);
            // 删除任务
            sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param context
     * @Description: 移除一个任务
     */
    public static void removeJob(JobExecutionContext context) {
        JobKey jobKey = context.getJobDetail().getKey();
        TriggerKey triggerKey = context.getTrigger().getKey();
        try {
            // 停止触发器
            context.getScheduler().pauseTrigger(triggerKey);
            // 移除触发器
            context.getScheduler().unscheduleJob(triggerKey);
            // 删除任务
            context.getScheduler().deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }


    /**
     * @Description:启动所有定时任务
     */
    public static void startJobs() {
        try {
            sched.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:关闭所有定时任务
     */
    public static void shutdownJobs() {
        try {
            if (!sched.isShutdown()) {
                sched.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}